/**
 * Module dependencies.
 */
var fs = require('fs'); 
var accessLogfile = fs.createWriteStream('access.log', {flags: 'a'}); 
var errorLogfile = fs.createWriteStream('error.log', {flags: 'a'}); 
var flash = require('connect-flash');
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var MongoStore=require('connect-mongo')(express);
var setting=require('./setting');
var app = express();

module.exports=app;

app.configure(function(){
	app.set('env','production');
	app.use(express.logger({stream: accessLogfile}));
	app.use(function(err, req, res, next){
	  var meta = '[' + new Date() + '] ' + req.url + '\n';
	  errorLogfile.write(meta + err.stack + '\n');
	  next();
	}); 
	app.set('views', __dirname + '/views'); 
	app.set('view engine', 'ejs'); 
	//app.use(express.bodyParser()); 替换为以下2行：
	app.use(express.urlencoded());
	app.use(express.json());
	app.use(express.methodOverride()); 
	app.use(express.cookieParser()); 
	app.use(express.session({ 
		secret: setting.cookieSecret, 
		store: new MongoStore({ 
			db: setting.db
			}) 
		})
	);
	app.use(flash());
	//视图助手
	app.use(function(req, res, next){
	  res.locals.user = req.session.user;
	  var err = req.flash('error');
	  if(err.length)
		 res.locals.error = err;
	  else
		 res.locals.error = null;
	  var succ = req.flash('success');
	  if(succ.length)
		 res.locals.success = succ;
	  else
		 res.locals.success = null;
	
	  next();
	});
	app.use(app.router);
	app.use(express.static(__dirname + '/public')); 
}); 

routes(app);

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
};

app.prot=80;

http.createServer(app);

if (!module.parent) {
	app.listen(app.prot);
	console.log("Express server listening on port %d in %s mode", app.prot, app.settings.env);
}
